package www.dianbaozu.com.ui.server

import androidx.databinding.ObservableField
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import www.wen.com.common.R
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString


/**
 * @author WEN
 * @Description:创建新的服务器
 * @date 2020//25 17:48
 */
class InviteJoiningServerViewModel @ViewModelInject constructor(appDataManager: AppDataManager) :
        BaseApiViewModel(appDataManager) {

    val mServerIdOrServerName = ObservableField("")

    val mEnableJoinServer = ObservableField(false)

    fun onServerIdOrNameTextChanged() {
        mEnableJoinServer.set(!mServerIdOrServerName.get().isNullOrBlank())
    }

    fun requestInviteOrAdd(action:()->Unit) {
        viewModelScope.launch {
            loading.value = UiStateCustom(
                    stateData = LoadingDialog(
                            getString(R.string.being_added),
                            LoadingDialogStateType.LOADING
                    )
            )
            val result = appDataManager.requestInviteOrAdd("add", RequestBodyParameter(serverId = mServerIdOrServerName.get()))
            if (result is Result.Success) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = getString(R.string.success_added),
                                loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                isShowDialogTip = false,
                                isShowToastTip = true,
                                action = action
                        )
                )
            } else if (result is Result.Error) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = result.exception.message?:getString(R.string.failed_added),
                                loadingDialogStateType = LoadingDialogStateType.ERROR,
                                isShowDialogTip = false,
                                isShowToastTip = true
                        )
                )
            }
        }
    }




}


